package org.example.studentmanager.service;

import org.example.studentmanager.model.Root;
import org.example.studentmanager.model.User;
import org.example.studentmanager.repository.RootRepository;
import org.example.studentmanager.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;

@Service
public class UserService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RootRepository rootRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("Trying to load user by username: {}", username);
        // 先从管理员表中查找
        Optional<User> optionalUser = userRepository.findByUsername(username);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(user.getRole()));
            logger.info("Found user {} with role {} in users table", username, user.getRole());
            return new org.springframework.security.core.userdetails.User(
                    user.getUsername(),
                    user.getPassword(),
                    authorities);}
        // 再从普通用户表中查找
        Optional<Root> optionalRoot = rootRepository.findByUsername(username);
        if (optionalRoot.isPresent()) {
            Root root = optionalRoot.get();
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(root.getRole()));
            logger.info("Found user {} with role {} in roots table", username, root.getRole());
            return new org.springframework.security.core.userdetails.User(
                    root.getUsername(),
                    root.getPassword(),
                    authorities);}
        logger.error("User not found with username: {}", username);
        throw new UsernameNotFoundException("User not found with username: " + username);
    }

    // 添加保存普通用户的方法
    public void saveRoot(Root root) {
        logger.info("Saving user {} to roots table", root.getUsername());
        root.setPassword(passwordEncoder.encode(root.getPassword()));
        rootRepository.save(root);
    }

    // 添加保存管理员的方法
    public void saveUser(User user) {
        logger.info("Saving user {} to users table", user.getUsername());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

    public UserDetails loadUserByUsernameAndRole(String username, String role) throws UsernameNotFoundException {
        logger.info("Trying to load user by username: {} and role: {}", username, role);
        if ("ADMIN".equals(role)) {
            Optional<User> optionalUser = userRepository.findByUsername(username);
            if (optionalUser.isPresent()) {
                User user = optionalUser.get();
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority(user.getRole()));
                logger.info("Found user {} with role {} in users table", username, user.getRole());
                return new org.springframework.security.core.userdetails.User(
                        user.getUsername(),
                        user.getPassword(),
                        authorities
                );}
        } else if ("USER".equals(role)) {
            Optional<Root> optionalRoot = rootRepository.findByUsername(username);
            if (optionalRoot.isPresent()) {
                Root root = optionalRoot.get();
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority(root.getRole()));
                logger.info("Found user {} with role {} in roots table", username, root.getRole());
                return new org.springframework.security.core.userdetails.User(
                        root.getUsername(),
                        root.getPassword(),
                        authorities);}}
        logger.error("User not found with username: {} and role: {}", username, role);
        throw new UsernameNotFoundException("User not found with username: " + username + " and role: " + role);
    }
}